package com.qw.qrweb.mapper;

import com.qw.qrweb.model.dto.DayVisits;
import com.qw.qrweb.model.dto.RegionDTO;
import com.qw.qrweb.model.entity.LogEntity;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface LogMapper {

    @Insert("insert into logs values (null, #{ip}, #{time }, null)")
    int addLog(String ip, LocalDateTime time);

    @Select("select * from logs")
    List<LogEntity> getLogs();

    @Select("SELECT * FROM logs WHERE DATE(time) = CURDATE()")
    List<LogEntity> getLogsToday();

    @Select("SELECT * FROM logs WHERE time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)")
    List<LogEntity> getLogsLastHour();

    @Select("SELECT * FROM logs WHERE time >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)")
    List<LogEntity> getLogsLast5Minutes();

    @Select("SELECT * FROM logs WHERE time >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)")
    List<LogEntity> getLogsLast10Minutes();

    @Select("SELECT * FROM logs WHERE time >= DATE_SUB(NOW(), INTERVAL 30 MINUTE )")
    List<LogEntity> getLogsLast30Minutes();

    @Select("SELECT DATE(time) as day, COUNT(*) as visits " +
            "FROM logs " +
            "WHERE time >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK) AND time < CURDATE() " +
            "GROUP BY DATE(time) " +
            "ORDER BY day")
    List<DayVisits> getVisitsLastWeek();

    // 获取昨天每小时的访问统计
    @Select("SELECT DATE_FORMAT(time, '%H:00') AS hour, COUNT(*) AS count "
            + "FROM logs "
            + "WHERE time BETWEEN CONCAT(CURDATE() - INTERVAL 1 DAY, ' 00:00:00') AND CONCAT(CURDATE() - INTERVAL 1 DAY, ' 23:59:59') "
            + "GROUP BY hour "
            + "ORDER BY hour")
    List<LogEntity> getHourlyTrafficStats();

    // 获取今天每小时的访问统计
    @Select("SELECT DATE_FORMAT(time, '%H:00') AS hour, COUNT(*) AS count " +
            "FROM logs " +
            "WHERE time >= CURDATE() AND time < CURDATE() + INTERVAL 1 DAY " +
            "GROUP BY hour " +
            "ORDER BY hour")
    List<LogEntity> getHourlyTrafficStatsToday();

    @Select("SELECT region, COUNT(*) as count FROM logs GROUP BY region ORDER BY count DESC")
    List<RegionDTO> getLogsRegions();

    @Select("SELECT * FROM logs WHERE region IS NULL OR region = ''")
    List<LogEntity> findLogsWithEmptyRegion();

    @Update("UPDATE logs SET region = #{region} WHERE id = #{id}")
    int updateLogRegion(@Param("id") long id, @Param("region") String region);

    @Select("SELECT COUNT(*) FROM logs WHERE time > #{updateTime}")
    int countViewsAfterUpdateTime(@Param("updateTime") LocalDateTime updateTime);

}
